import {observable, extendObservable, action, toJS} from 'mobx';
import {addUserInfo, updateUserInfo} from 'util/api';
import _ from 'lodash';
import {validateFields, getParams} from '../Common.js';
import {message} from 'antd';
import store from 'store';

//导出
export default class AddUnit {
  constructor() {
    this.reset(true);
    this.mediaStreamTrack = null;
  }

  @action
  reset = init => {
    const state = {
      type: 'new',
      fields: {
        cname: {
          value: '',
          require: true,
        },
        phone: {value: '', require: false},
        idCard: {value: '', require: false},
        sex: {value: '男', require: true},
        unitId: {value: '', require: true},
        userType: {value: 1, require: true},
      },

      imageUrl: require('image/user-photo.png'),
      file: null,
      currentData: {},
    };

    if (init) {
      extendObservable(this, state);
    } else {
      Object.keys(state).forEach(key => (this[key] = state[key]));
    }

    this.location = {};
    this.match = {};
    this.history = {};
  };

  //取消新增单元
  @action
  resetFields = async () => {
    this.fields = {
      cname: {
        value: '',
        require: true,
      },
      phone: {value: '', require: false},
      idCard: {value: '', require: false},
      sex: {value: '男', require: true},
      unitId: {value: '', require: true},
      userType: {value: 1, require: true},
    };
  };

  @action
  usersOk = async (cancle, store) => {
    //校验字段
    validateFields(
      toJS(this.fields),
      async fields => {
        let params = getParams(fields);
        params['name'] = params.cname;
        delete params['cname'];
        this.file && (params['file'] = this.file);
        console.log(params);
        this.type === 'edit' && (params['userId'] = this.currentData['userId']);

        let res = await (this.type === 'new'
          ? addUserInfo(params)
          : updateUserInfo(params));
        if (res.result === 'success') {
          cancle();
          message.success(res.msg);
          store.getUserInfo();
        }
      },
      newFields => {
        this.fields = newFields;
      },
    );
  };
  //改变字段
  @action
  handleFormChange = async changedFields => {
    const key = _.keys(changedFields);
    //showError让自己校验字段;
    const obj = {};
    obj[key] = {showError: false, ...changedFields[key]};
    this.fields = {...toJS(this.fields), ...obj};
  };
  //显示新增单元删除
  @action
  newUsers = async () => {
    //清空fields
    this.resetFields();
    this.file = null;
    this.imageUrl = require('image/user-photo.png');
    this.type = 'new';
    store.CommonModalStore.confim('new');
  };
  @action
  editUsers = async record => {
    //清空fields
    this.resetFields();
    this.file = null;
    this.imageUrl = require('image/user-photo.png');
    this.currentData = record;
    let obj = toJS(this.fields);
    obj['cname'].value = record.name || '';
    obj['phone'].value = record.phone || '';
    obj['sex'].value = record.sex || '男';
    obj['userType'].value = record.userType || 1;
    obj['idCard'].value = record.idCard || '';
    obj['unitId'].value = record.unitId || '';
    this.fields = obj;
    this.type = 'edit';
    store.CommonModalStore.confim('edit');
  };
  @action
  changePassword = async record => {
    let fields = toJS(this.fields);
  };
  @action
  changeImageUrl = (url, file) => {
    this.imageUrl = url;
    this.file = file;
  };

  //调用相机方法
  success = stream => {
    let video = document.getElementById('peace-video');
    //兼容webkit核心浏览器
    let CompatibleURL = window.URL || window.webkitURL;
    //将视频流设置为video元素的源
    this.mediaStreamTrack = stream.getTracks()[0];
    //video.src = CompatibleURL.createObjectURL(stream);
    video.srcObject = stream;
    video.play();
  };

  error = error => {
    message.error('访问用户媒体设备失败,请尝试更换浏览器');
  };
  //访问用户媒体设备的兼容方法
  getUserMedia = (constraints, success, error) => {
    if (navigator.mediaDevices.getUserMedia) {
      //最新的标准API
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(success)
        .catch(error);
    } else if (navigator.webkitGetUserMedia) {
      //webkit核心浏览器
      navigator.webkitGetUserMedia(constraints, success, error);
    } else if (navigator.mozGetUserMedia) {
      //firfox浏览器
      navigator.mozGetUserMedia(constraints, success, error);
    } else if (navigator.getUserMedia) {
      //旧版API
      navigator.getUserMedia(constraints, success, error);
    }
  };
  @action
  turnOff = () => {
    this.mediaStreamTrack && this.mediaStreamTrack.stop();
  };
  @action
  takePictures = () => {
    let video = document.getElementById('peace-video');
    let canvas = document.createElement('canvas');
    let context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, 1024, 2048, 0, 0, 561, 561);

    //将base64转换为文件对象
    function dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(',');
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      //转换成file对象
      return new File([u8arr], filename, {type: mime});
      //转换成成blob对象
      //return new Blob([u8arr],{type:mime});
    }
    let url = canvas.toDataURL('image/png');

    this.changeImageUrl(url, dataURLtoFile(url, 'file.png'));

    this.mediaStreamTrack && this.mediaStreamTrack.stop();
  };
  @action
  requestCamera = video => {
    if (
      navigator.mediaDevices.getUserMedia ||
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia
    ) {
      //调用用户媒体设备, 访问摄像头
      this.getUserMedia(
        {
          video: {
            width: 561,
            height: 561,
          },
        },
        this.success,
        this.error,
      );
      store.CommonModalStore.confim('taking-pictures');
    } else {
      alert('不支持访问用户媒体');
    }
  };
}
